package testfile;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.gushiyingxiong.R;
import com.gushiyingxiong.app.base.ShBaseTitleFragmentActivity;
import com.gushiyingxiong.app.constants.ShConstants;
import com.gushiyingxiong.app.constants.ShIntent;
import com.gushiyingxiong.app.entry.MoneyRate;
import com.gushiyingxiong.app.entry.ShError;
import com.gushiyingxiong.app.entry.Stock;
import com.gushiyingxiong.app.entry.StockOrder;
import com.gushiyingxiong.app.entry.User;
import com.gushiyingxiong.app.preference.AppPref;
import com.gushiyingxiong.app.setting.Pay;
import com.gushiyingxiong.app.setting.SettingHttpTask;
import com.gushiyingxiong.app.user.UserManager;
import com.gushiyingxiong.app.utils.AutoRefreshTimer;
import com.gushiyingxiong.app.utils.AutoRefreshTimer.AutoRefreshListener;
import com.gushiyingxiong.app.utils.DialogUtil;
import com.gushiyingxiong.app.utils.JsonFileUtil;
import com.gushiyingxiong.app.utils.ShJson;
import com.gushiyingxiong.app.utils.StockUtil;
import com.gushiyingxiong.app.views.LoadingDialog;
import com.gushiyingxiong.app.views.NormalAlertDialog;
import com.gushiyingxiong.app.views.PayDialog;
import com.gushiyingxiong.app.views.PayDialog.OnPayClickListener;
import com.gushiyingxiong.common.base.AppException;
import com.gushiyingxiong.common.utils.DLog;
import com.gushiyingxiong.common.utils.StringUtil;
import com.iapppay.mpay.ifmgr.SDKApi;

/**
 * 描述:买入
 * <p>
 * 接收一个Stock Bundle(即key为stock，value为Stock类型对象)
 * 
 * @author mfx
 * @date 2014年5月2日 下午11:06:59
 */
public class BuyActivity extends ShBaseTitleFragmentActivity implements
		OnSeekBarChangeListener, OnClickListener, OnTouchListener,
		OnPayClickListener,AutoRefreshListener {

	private static final int MSG_SUBMIT = 0x10100;
	private static final int MSG_SUBMIT_SUCCESS = 0x10101;
	private static final int MSG_SUBMIT_FAILED = 0x10102;

	private static final int MSG_REQUEST_DATA = 0x10103;
	private static final int MSG_REQUEST_SUCCESS = 0x10104;
	private static final int MSG_REQUEST_FAIED = 0x10105;

	private static final int MSG_REQUSET_PAY_ORDER_NUMBER = 0x10106;
	private static final int MSG_REQUEST_PAY_ORDER_NUMBER_OK = 0x10107;
	private static final int MSG_REQUEST_PAY_ORDER_NUMBER_FAILED = 0x10108;

	private EditText mEdtReason;
	private TextView mTvNewPrice;
	private TextView mTvChangePercent;
	private EditText mEdtUintPrice;
	private EditText mEdtAmount;
	private TextView mTvTotalPrice;
	private TextView mTvBalance;
	private TextView mTvServiceFee;
	private TextView mTvDealPrice;
	private TextView mTvReasonLength;
	private SeekBar mSbarAmout;

	/** 最新价格 */
	private float mNewPrice = 10.0f;

	/** 买入价格 */
	private float mUnitPrice;

	/** 股票总价 */
	private float mTotalPrice = 0;

	/** 买入数量 */
	private int mAmount = 0;

	/** 余额 */
	private float mBalance = 0;

	/** 最多可买入数量，根据余额除以买入价格 */
	private int mMaxAmount;

	/** 滑动条步长 */
	private int mStepSize = 100;

	/** 手续费 */
	private float mServiceFee = 0.0f;

	private float mDealPrice = 0.0f;

	private Stock mStock;
	private User mUser;

	private TextView mTvSubmit;
	private TextView mTvSymbol;
	private TextView mTvExchangeRate;

	private String mReason;
	private MoneyRate mMoneyRate;
	private float mExchangeRate = 1.0f;
	private LoadingDialog mLoadingDialog;
	private long mBeginTime, mTakeTime;
	private View mVBuyLayout;
	private ImageView mIvRefresh;
	private ImageView mIvPay;
	private ProgressBar mProgressBar;

	/** 支付订单号 */
	private String mPayOrderNum = "";

	/** 购买类型 */
	private int mBuyWhat;
	private boolean mIsPreGet = false;

	/** 是否加载过 */
	private boolean mIsLoaded = false; // 没加载过需要显示reloadview
	private boolean mIsLoading = false;
	private boolean mIsAutoRefresh = true;
	private boolean mIsFirstTime = true;
	
	PayDialog mPayDialog;
	
	private AutoRefreshTimer mAutoRefreshTimer;
	private boolean mIsSmallPrice = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buy);
		enableBackBtn();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.containsKey("stock")) {
			mStock = (Stock) bundle.get("stock");
		}

		initView();

		if (mStock != null) {
			setActTitle(mStock.name);
			mTvSymbol.setText(mStock.symbol);
		}

		mUser = UserManager.getInstance().getUser();
		mMoneyRate = getMoneyRate();
		mServiceFee = mMoneyRate.lowServiceFee;
		addTextWatcher();
	}

	private void initView() {
		mTvSubmit = (TextView) findViewById(R.id.title_bar_right_tv);
		mTvReasonLength = (TextView) findViewById(R.id.buy_reason_text_count);
		mTvSymbol = (TextView) findViewById(R.id.title_bar_title_tv_small);
		mTvSubmit.setText(R.string.submit);
		mTvSubmit.setEnabled(false);
		mEdtReason = (EditText) findViewById(R.id.buy_reason);
		mTvNewPrice = (TextView) findViewById(R.id.buy_newest_price);
		mTvChangePercent = (TextView) findViewById(R.id.buy_change_percent);
		mProgressBar = (ProgressBar)findViewById(R.id.buy_progress);
		mEdtUintPrice = (EditText) findViewById(R.id.buy_unit_price);
		mEdtAmount = (EditText) findViewById(R.id.buy_in_amount);
		mTvTotalPrice = (TextView) findViewById(R.id.buy_total_price);
		mTvBalance = (TextView) findViewById(R.id.buy_balance);
		mTvServiceFee = (TextView) findViewById(R.id.buy_service_fee);
		mTvDealPrice = (TextView) findViewById(R.id.buy_deal_price);
		mTvExchangeRate = (TextView) findViewById(R.id.buy_exchange_rate);
		mSbarAmout = (SeekBar) findViewById(R.id.buy_seek_bar);
		mVBuyLayout = findViewById(R.id.buy_detail_layout);
		mIvRefresh = (ImageView) findViewById(R.id.buy_refresh);
		mIvPay = (ImageView) findViewById(R.id.buy_pay);
		mIvRefresh.setOnClickListener(this);
		mSbarAmout.setOnSeekBarChangeListener(this);
		mTvSubmit.setOnClickListener(this);
		mVBuyLayout.setOnTouchListener(this);
		mIvPay.setOnClickListener(this);
		mEdtReason.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				mTvReasonLength.setText(String.valueOf(140 - s.length()));
			}
		});

		mEdtReason.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
			}
		});
	}

	private void initData() {
		mIsSmallPrice =StockUtil.isSmallPrice(mStock);
		mNewPrice = mStock.trade;
		mBalance = mUser.pointRemainder;
		String s = getString(R.string.exchange_rate);
		mExchangeRate = getExchangeRate();
		mStepSize = getSeekbarStepSize();
		mUnitPrice = mNewPrice;
		mDealPrice = mTotalPrice + mServiceFee;
		
		if (mStock.region == Stock.REGION_CHINA) {
			mTvExchangeRate.setVisibility(View.INVISIBLE);
		} else {
			mTvExchangeRate.setText(String.format(s, formatFloat(mExchangeRate)));
		}

		mTvNewPrice.setText(StringUtil.formatMoney(formatFloat(mNewPrice),mStock.region));
		s = String.format("(%s)",StringUtil.formatSymbolPercent(mStock.changePercent));
		mTvChangePercent.setText(s);
		StockUtil.setStockTextColor(mTvChangePercent, mStock.changePercent);
		mEdtUintPrice.setText(formatFloat(mUnitPrice));
		mEdtAmount.setText(String.valueOf(mAmount));
		mTvTotalPrice.setText(formatToRmb(formatFloat(mTotalPrice)));
		mTvBalance.setText(formatToRmb(formatFloat(mBalance)));
		mTvServiceFee.setText(formatToRmb(formatFloat(mServiceFee)));
		mTvDealPrice.setText(formatToRmb(formatFloat(mDealPrice)));

		if (mMaxAmount < mStepSize) {
			mSbarAmout.setMax(0);
		} else {
			mSbarAmout.setMax(mMaxAmount);
		}

		checkShowPriceGuide();
		if (!checkBalance()) {
			showChargeAlertDialog();
		}
	}
	
	private String formatFloat(float value){
		if(mIsSmallPrice){
			return StringUtil.formatFloat3(value);
		}else{
			return StringUtil.formatFloat2(value);
		}
	}
	
	private String formatToRmb(String value){
		return StringUtil.formatMoneyRmb(value);
	}
	
	/**
	 * 显示充值提醒对话框
	 */
	private void showChargeAlertDialog(){
		final NormalAlertDialog alertDialog = new NormalAlertDialog(this);
		alertDialog.setTitle(R.string.tip);
		if (mStock.region != Stock.REGION_USA) {
			alertDialog.setText(R.string.no_money_to_buy_cn);
		} else {
			alertDialog.setText(R.string.no_money_to_buy_us);
		}
		alertDialog.setLeftBtn(R.string.cancel, new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		alertDialog.setRightBtn(R.string.buy_now,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						alertDialog.dismiss();
						BuyActivity.this.onClick(mIvPay);
					}
				});
		alertDialog.show();
	}
	
	/**
	 * 获取汇率，手续费，税费实体
	 * @return
	 */
	private MoneyRate getMoneyRate(){
		String s = JsonFileUtil.readJson(this, ShJson.MONEY_RATE);
		MoneyRate moneyRate = new MoneyRate();
		moneyRate.resolveJson(s);
		return moneyRate;
	}
	
	/**
	 * 获取汇率
	 * @return
	 */
	private float getExchangeRate(){
		float result;
		if (mStock.region == Stock.REGION_HK) {
			result = mMoneyRate.HKDCNY;
		} else if (mStock.region == Stock.REGION_USA) {
			result = mMoneyRate.USDCNY;
		} else {
			result = 1.0f;// 人民币自身
		}
		return result;
	}
	
	/**
	 * 获取步长
	 * @return
	 */
	private int getSeekbarStepSize(){
		int stepSize;
		if (mStock.region == Stock.REGION_HK) {
			stepSize = 100;
		} else if (mStock.region == Stock.REGION_USA) {
			stepSize = 1;
		} else {
			stepSize = 100;
		}
		return stepSize;
	}
	
	private void setData(){
		mNewPrice = mStock.trade;
		mTvNewPrice.setText(StringUtil.formatMoney(formatFloat(mNewPrice), mStock.region));
		StockUtil.setStockTextColor(mTvChangePercent, mStock.changePercent);
		String s = String.format("(%s)", StringUtil.formatSymbolPercent(mStock.changePercent));
		mTvChangePercent.setText(s);
	}

	/**
	 * 获取最多可买入数量
	 * 
	 * @param balance 余额
	 * @param unitPrice 买入价格
	 * @return
	 */
	private int getMaxAmount(float balance, float unitPrice) {
		if (unitPrice == 0) {
			return mMaxAmount;
		}
		int maxAmount = (int) (balance / (unitPrice + unitPrice * mMoneyRate.serviceFeePercent));
		float serviceFee = (int) (maxAmount * unitPrice * mMoneyRate.serviceFeePercent);
		if (serviceFee < 5) {
			return (int) ((balance - 5) / unitPrice);
		} else {
			return maxAmount;
		}

	}
	
	/**
	 * 价格提醒
	 */
	private void checkShowPriceGuide(){
		if (mStock.region == Stock.REGION_USA && !AppPref.getInstance().getUsPriceGuide()) {
			ViewStub mVsGuide = (ViewStub) findViewById(R.id.buy_viewstub);
			if (mVsGuide != null) {
				mVsGuide.inflate();
				TextView text = (TextView) findViewById(R.id.guide_text);
				text.setText(R.string.guide_us_price);
				ImageView ivGuideClose = (ImageView) findViewById(R.id.guide_close);
				ivGuideClose.setOnClickListener(this);
				Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);  
				text.startAnimation(shake);
			}
		} else if (mStock.region == Stock.REGION_HK && !AppPref.getInstance().getHkPriceGuide()) {
			ViewStub mVsGuide = (ViewStub) findViewById(R.id.buy_viewstub);
			if (mVsGuide != null) {
				mVsGuide.inflate();
				TextView text = (TextView) findViewById(R.id.guide_text);
				text.setText(R.string.guide_hk_price);
				ImageView ivGuideClose = (ImageView) findViewById(R.id.guide_close);
				ivGuideClose.setOnClickListener(this);
				Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);  
				text.startAnimation(shake);
			}
		}
	}
	
	
	private void hidePriceGuide(){
		View guideView = findViewById(R.id.viewstub_inflateid);
		if (guideView != null) {
			if(mStock.region == Stock.REGION_USA){
				guideView.setVisibility(View.GONE);
				AppPref.getInstance().putUsPriceGuide(true);
			}else if(mStock.region  == Stock.REGION_HK){
				guideView.setVisibility(View.GONE);
				AppPref.getInstance().putHkPriceGuide(true);
			}
			
		}
	}

	private void addTextWatcher() {
		mEdtUintPrice.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s != null) {
					try {
						mUnitPrice = Float.valueOf(s.toString().trim());
					} catch (NumberFormatException e) {
						mUnitPrice = mNewPrice;
					}
					mMaxAmount = getMaxAmount(mBalance / mExchangeRate,
							mUnitPrice);
					if (mMaxAmount < mStepSize) {
						mSbarAmout.setMax(0);
					} else {
						mSbarAmout.setMax(mMaxAmount);
						mSbarAmout.setProgress(0);
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		mEdtAmount.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (s != null) {
					try {
						mAmount = Integer.valueOf(s.toString().trim());
					} catch (NumberFormatException e) {
						mAmount = 0;
					}
					mTotalPrice = mAmount * mUnitPrice * mExchangeRate;
					mServiceFee = mTotalPrice * mMoneyRate.serviceFeePercent;
					if (mServiceFee < mMoneyRate.lowServiceFee) {
						mServiceFee = mMoneyRate.lowServiceFee;
					}
					mDealPrice = mTotalPrice + mServiceFee;

					setPrices(mTotalPrice, mServiceFee, mDealPrice);
					togleSubmitBtnStatus();

				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		mEdtUintPrice.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					String s = mEdtUintPrice.getText().toString();
					if (StringUtil.isEmpty(s)
							|| (s.length() == 1 && s.equals("."))) {
						mEdtUintPrice.setText(String.valueOf(mNewPrice));
					}
				}
			}
		});

		mEdtAmount.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					String s = mEdtAmount.getText().toString();
					if (StringUtil.isEmpty(s)) {
						mEdtAmount.setText(String.valueOf(0));
					}
				}
			}
		});
	}

	private void setPrices(float totalPrice, float serviceFee, float dealPrice) {
		mTvTotalPrice.setText(formatToRmb(formatFloat(totalPrice)));
		mTvDealPrice.setText(formatToRmb(formatFloat(dealPrice)));
		mTvServiceFee.setText(formatToRmb(formatFloat(serviceFee)));
	}

	private void togleSubmitBtnStatus() {
		if (mTotalPrice <= 0) {
			if (mTvSubmit.isEnabled()) {
				mTvSubmit.setEnabled(false);
			}
		} else {
			if (!mTvSubmit.isEnabled()) {
				mTvSubmit.setEnabled(true);
			}
		}
	}

	@Override
	protected void onReloadClick(View v) {
		super.onReloadClick(v);
		showLoadingView();
		setRefreshing(true);
	}

	@Override
	protected void handleUiMessage(Message msg) {
		int what = msg.what;
		dismissLoadingDlg();
		switch (what) {
		case MSG_SUBMIT_SUCCESS:
			sendBroadcast(new Intent(ShIntent.ACTION_BUY_STOCK));
			Intent intent = new Intent(this, OrderResultActivity.class);
			StockOrder order = (StockOrder) msg.obj;
			order.region = mStock.region;
			intent.putExtra("order", order);
			startActivity(intent);
			finish();
			break;
		case MSG_SUBMIT_FAILED:
			DialogUtil.showToast(this, String.valueOf(msg.obj));
			break;
		case ShError.NETWORK_ERROR:
			DialogUtil.showNetworkErrorToast(this);
			setRefreshing(false);
			break;
		case MSG_REQUEST_SUCCESS:
			if(mIsFirstTime){
				mIsFirstTime = false;
				if(mStock!=null && mUser!=null){
					initData();
				}
			}else if(mStock!=null){
				setData();
			}
			
			showMainView();
			mIsLoaded = true;
			setRefreshing(false);
			break;
		case MSG_REQUEST_FAIED:
			if (!mIsLoaded) {
				showReloadView();
			}
			setRefreshing(false);
			break;
		case MSG_REQUEST_PAY_ORDER_NUMBER_OK:
			Pay.startPay(this, UserManager.getInstance().getUser().uid,
					mBuyWhat, mPayOrderNum);
			break;
		case MSG_REQUEST_PAY_ORDER_NUMBER_FAILED:
			DialogUtil.showToast(this, R.string.get_pay_order_num_failed);
			break;
		default:
			break;
		}
	}

	@Override
	protected void handleBackgroundMessage(Message msg) {
		switch (msg.what) {
		case MSG_SUBMIT:
			mReason = mEdtReason.getText().toString().trim();
			mUnitPrice = Float.valueOf(mEdtUintPrice.getText().toString()
					.trim());
			mAmount = Integer.valueOf(mEdtAmount.getText().toString().trim());
			OrderHttpTask buyHttpTask = new OrderHttpTask();
			OrderResponse response;
			try {
				response = buyHttpTask.buy(mStock.symbol, mUnitPrice, mAmount,
						mReason);
				if (response.isOk()) {
					StockOrder order = response.getBuyOrder();
					mTakeTime = System.currentTimeMillis() - mBeginTime;
					if (order != null) {
						if (order.status == StockOrder.STATUS_DEAL_SUCCESS) {

						} else if (order.status == StockOrder.STATUS_DEAL_FAILED) {

						}

						Message message = Message.obtain();
						message.what = MSG_SUBMIT_SUCCESS;
						message.obj = order;
						sendUiMessageDelayed(message,
								DialogUtil.DIALOG_SHOW_MININUM_TIME - mTakeTime);
						return;
					}
				} else {
					Message message = Message.obtain();
					message.what = MSG_SUBMIT_FAILED;
					message.obj = response.getError();
					sendUiMessage(message);
				}

			} catch (AppException e) {
				e.printStackTrace();
				sendEmptyUiMessage(ShError.NETWORK_ERROR);
			}

			break;

		case MSG_REQUEST_DATA:
			mIsLoading = true;
			DetailHttpTask task = new DetailHttpTask();
			try {
				Stock stock = task.requestBuyData(mStock.symbol);
				mTakeTime = System.currentTimeMillis() - mBeginTime;
				if (stock != null) {
					mStock = stock;
					sendEmptyUiMessageDelayed(MSG_REQUEST_SUCCESS,
							DialogUtil.DIALOG_SHOW_MININUM_TIME - mTakeTime);
				} else {
					sendEmptyUiMessageDelayed(MSG_REQUEST_FAIED,
							DialogUtil.DIALOG_SHOW_MININUM_TIME - mTakeTime);
				}
			} catch (AppException e) {
				e.printStackTrace();
				if (!mIsLoaded) {
					sendEmptyUiMessage(MSG_REQUEST_FAIED);
				}
				sendEmptyUiMessage(ShError.NETWORK_ERROR);
			} finally {
				mIsLoading = false;
			}
			break;
		case MSG_REQUSET_PAY_ORDER_NUMBER:
			SettingHttpTask payTask = new SettingHttpTask();
			try {
				mPayOrderNum = payTask.requestPayOrderNum();
				DLog.d("pay order:" + mPayOrderNum);
				if (!StringUtil.isEmpty(mPayOrderNum)) {
					sendEmptyUiMessage(MSG_REQUEST_PAY_ORDER_NUMBER_OK);
				} else {
					sendEmptyUiMessage(MSG_REQUEST_PAY_ORDER_NUMBER_FAILED);
				}
			} catch (AppException e) {
				e.printStackTrace();
				sendEmptyUiMessage(ShError.NETWORK_ERROR);
			}
			break;

		default:
			break;
		}
	}

	/**
	 * 检查买入数量是否正确
	 * 
	 * @return
	 */
	private boolean checkAmount() {
		if (mStock.region != Stock.REGION_USA) {
			if ((mAmount) > 0 && (mAmount % 100)==0) {
				return true;
			}
		} else {
			if (mAmount > 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 检查余额是否足够
	 * 
	 * @return
	 */
	private boolean checkBalance() {
		if (mStock.region != Stock.REGION_USA) {
			if (mBalance > (mUnitPrice * 100)) {
				return true;
			}
		} else {
			if (mBalance > (mUnitPrice * mExchangeRate)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.title_bar_right_tv:
			submit();
			break;
		case R.id.buy_refresh:
			refreshData();
			break;
		case R.id.buy_pay:
			showPayDialog();
			break;
		case R.id.guide_close:
			hidePriceGuide();
			break;
		default:
			break;
		}
	}
	
	private void submit() {
		if (!checkAmount()) {
			final NormalAlertDialog alertDialog = new NormalAlertDialog(this);
			alertDialog.setOneBtn(R.string.confirm, new OnClickListener() {

				@Override
				public void onClick(View v) {
					alertDialog.dismiss();
				}
			});
			alertDialog.setTitle(R.string.buy_amount_invalid_tip);
			alertDialog.show();
		} else {
			if (mDealPrice > mBalance) {
				final NormalAlertDialog alertDialog = new NormalAlertDialog(
						this);
				alertDialog.setLeftBtn(R.string.cancel, new OnClickListener() {

					@Override
					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});

				alertDialog.setRightBtn(R.string.buy_now,
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								alertDialog.dismiss();
								BuyActivity.this.onClick(mIvPay);
							}
						});
				alertDialog.setTitle(R.string.tip);
				alertDialog.setText(R.string.no_money);
				alertDialog.show();
			} else {
				mBeginTime = System.currentTimeMillis();
				mLoadingDialog = DialogUtil.getLoadingDialg(this);
				mLoadingDialog.setText(R.string.submit_loading);
				mLoadingDialog.show();
				sendEmptyBackgroundMessage(MSG_SUBMIT);
			}
		}
	}
	
	private void showPayDialog(){
		if(mPayDialog==null){
			mPayDialog = new PayDialog(this, PayDialog.PAY_FOR_VIRTUAL_MONEY);
			mPayDialog.setOnPayClickListener(this);
		}
		mPayDialog.show();
	}

	private void dismissLoadingDlg() {
		if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
		mLoadingDialog = null;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {

		mAmount = (((int) Math.round(progress / mStepSize)) * mStepSize);
		mEdtAmount.setText(String.valueOf(mAmount));
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		hideInputMethod();
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (v.getId() == R.id.buy_detail_layout) {
				hideInputMethod();
			}
		}
		return false;
	}

	private void hideInputMethod() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEdtReason.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(mEdtAmount.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(mEdtUintPrice.getWindowToken(), 0);
		mEdtAmount.clearFocus();
		mEdtReason.clearFocus();
		mEdtUintPrice.clearFocus();
	}

	@Override
	public void onPayClick(int buyWhat) {
		mLoadingDialog = new LoadingDialog(this);
		mLoadingDialog.setText(R.string.get_pay_order_num_loading);
		try {
			mLoadingDialog.show();
		} catch (Exception e) {
		}

		if (!mIsPreGet) {
			/** 爱贝支付预加载 */
			SDKApi.preGettingData(this);
			mIsPreGet = true;
		}
		mBuyWhat = buyWhat;
		sendEmptyBackgroundMessage(MSG_REQUSET_PAY_ORDER_NUMBER);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (checkAutoRefresh()) {
			refreshData();
		}
		startAutoRefreshTimer();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		stopAutoRefreshTimer();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mPayDialog!=null){
			if(mPayDialog.isShowing()){
				mPayDialog.dismiss();
			}
			mPayDialog = null;
		}
		if(mLoadingDialog!=null){
			if(mLoadingDialog.isShowing()){
				mLoadingDialog.dismiss();
			}
			mLoadingDialog = null;
		}
		stopAutoRefreshTimer();
	}
	

	/**
	 * 是否应自动刷新
	 * 
	 * @return
	 */
	private boolean checkAutoRefresh() {
		if (!mIsLoading && mIsAutoRefresh) {
			return true;
		} else {
			return false;
		}
	}

	private void setRefreshing(boolean isRefreshing){
		if(isRefreshing){
			mProgressBar.setVisibility(View.VISIBLE);
			mIvRefresh.setVisibility(View.INVISIBLE);
		}else{
			mProgressBar.setVisibility(View.INVISIBLE);
			mIvRefresh.setVisibility(View.VISIBLE);
		}
	}
	
	private void refreshData() {
		DLog.d("买入页  刷新");
		mBeginTime = System.currentTimeMillis();
		setRefreshing(true);
		removeBackgroundMessages(MSG_REQUEST_DATA);
		sendEmptyBackgroundMessage(MSG_REQUEST_DATA);
	}
	
	private void stopAutoRefreshTimer() {
		if (mAutoRefreshTimer != null) {
			mAutoRefreshTimer.setOnAutoRefreshListener(null);
			mAutoRefreshTimer.cancel();
			mAutoRefreshTimer = null;
		}
	}

	private void startAutoRefreshTimer() {
		if (mIsAutoRefresh) {
			if (mAutoRefreshTimer == null) {
				mAutoRefreshTimer = new AutoRefreshTimer(ShConstants.TRADE_PAGE_REFRESH_INTERVAL);
				mAutoRefreshTimer.setOnAutoRefreshListener(this);
			}else{
				mAutoRefreshTimer.cancel();
			}
			mAutoRefreshTimer.start();
		}
	}
	
	@Override
	public void onAutoRefresh() {
		if(!mIsLoading){
			refreshData();
		}
		startAutoRefreshTimer();
	}

}
